package com.polarrose.spring.bayeux;

import org.springframework.beans.factory.InitializingBean;
import org.mortbay.cometd.Bayeux;
import org.mortbay.cometd.Channel;
import com.polarrose.spring.bayeux.util.JsonUtil;

public class BayeuxController implements InitializingBean
{
    /**
     * The configured name of the BayeuxServlet.
     */

    private String servletName;

    public void setServletName(String servletName)
    {
        this.servletName = servletName;
    }

    /**
     *
     */

    private Bayeux bayeux;

    Bayeux getBayeux()
    {
        return bayeux;
    }

    /**
     * Send an anonymous message to a bayeux destination.
     * @param destination
     * @param message
     */

    public void publish(BayeuxDestination destination, Object message)
    {
       Channel channel = getBayeux().getChannel(destination.getName());
        if (channel != null) {
            getBayeux().publish(
                channel.getId(),
                null,
                JsonUtil.transmogrify(message),
                "" // TODO What is msgId?
            );
        }
    }

    /**
     * Send a message to a bayeux destination.
     * @param destination
     * @param message
     * @param from
     */

    public void publish(BayeuxDestination destination, Object message, BayeuxClient from)
    {
       Channel channel = getBayeux().getChannel(destination.getName());
        if (channel != null) {
            getBayeux().publish(
                channel.getId(),
                from.getClient(),
                JsonUtil.transmogrify(message),
                "" // TODO What is msgId?
            );
        }
    }
    

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() 
     */

    public void afterPropertiesSet() throws Exception
    {
        if (servletName == null) {
            bayeux = BayeuxServlet.getDefaultBayeux();
        } else {
            bayeux = BayeuxServlet.getBayeuxByServletName(servletName);            
        }
    }
}
